package com.atguigu.lease.web.app.service.impl;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private Client client;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserInfoService userInfoService;

    //获取短信验证码
    @Override
    public void sentCode(String phone) throws Exception {

        //手机号key
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + phone;

        //0.检查手机验证码是否失效
        //方案1：验证码有效时间和redis存储一致
//        Boolean is = redisTemplate.hasKey(key);
//        if (is) {
//            throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
//        }
        //方案2：验证码有效时间600，二次发送的时间是60
        //1.是否有key
        Boolean is = redisTemplate.hasKey(key);
        if (is) {
            //获取剩余的有效时间
            Long expire = redisTemplate.getExpire(key, TimeUnit.SECONDS);
            //总的时间 - 剩余的有效时间 < 60  不能发送
            if (RedisConstant.APP_LOGIN_CODE_TTL_SEC - expire < RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC) {
                //没到间隔，不能发送
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }

        //1.生成一个随机的短信验证码（4位数字）Random
        Random random = new Random();
        //StringBuilder存放4位随机数字
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            int intValue = random.nextInt(10);  //范围从0-10
            stringBuilder.append(intValue);
        }
        //验证码code
        String code = stringBuilder.toString();

        //2.阿里短信验证发送验证码
        SendSmsRequest smsRequest = new SendSmsRequest();
        smsRequest.setPhoneNumbers(phone);
        smsRequest.setSignName("阿里云短信测试");
        smsRequest.setTemplateCode("SMS_154950909");
        smsRequest.setTemplateParam("{\"code\":\"" + code + "\"}\n");
        client.sendSms(smsRequest);

        //3.将验证码和手机存到redis中，手机号作为key
        redisTemplate.opsForValue().set(key, code, RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);
    }

    //登录判断
    @Override
    public String login(LoginVo loginVo) {

        //客户端的手机号
        String lv_phone = loginVo.getPhone();
        //客户端的验证码
        String lv_code = loginVo.getCode();

        //1.判断手机号和验证码是否为空
        //判断手机号
        if (!StringUtils.hasText(lv_phone)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        //判断验证码
        if (!StringUtils.hasText(lv_code)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }

        //2.判断验证码是否正确
        //校验验证码
        //客户端的key
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + lv_phone;
        //用客户端的key，从redis里查找到对应的code，再去跟客户端的code进行比较
        Object code = redisTemplate.opsForValue().get(key);

        //code如果为null，说明key过期被自动回收了
        if (code == null) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }

        //redis的code和客户端code不一致，说明验证码错误
        if (!code.equals(lv_code)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }

        //3.判断用户是否存在与数据库，不存在则注册（创建用户）
        LambdaQueryWrapper<UserInfo> userInfoVoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userInfoVoLambdaQueryWrapper.eq(UserInfo::getPhone, lv_phone);
        UserInfo userInfo = userInfoService.getOne(userInfoVoLambdaQueryWrapper);
        if (userInfo == null) {
            //创建新用户
            userInfo = new UserInfo();
            //用户手机
            userInfo.setPhone(lv_phone);
            //用户状态
            userInfo.setStatus(BaseStatus.ENABLE);
            //用户昵称
            userInfo.setNickname("昵称" + lv_phone.substring(5));
            //保存新用户信息
            userInfoService.save(userInfo);
        }

        //4.判断用户是否被禁用，查找status
        if (!userInfo.getStatus().equals(BaseStatus.ENABLE)) {
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }

        //5.创建并返回token
        return JwtUtil.createToken(userInfo.getId(), userInfo.getPhone());

    }
}



































